package com.xudow.app.ui.task;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;

import com.activeshare.edu.ucenter.common.messages.Message;
import com.xudow.app.Config;

import com.xudow.app.XApplication;
import com.xudow.app.util.StringUtils;
import com.xudow.app.util.rest.XRestTemplate;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * 获取验证码 task
 *
 * @author lukecheng
 */
public class VcodeTask extends AsyncTask<HashMap<String, String>, Void, Void> {
    private static final String TAG = makeLogTag(VcodeTask.class);

    //获取验证码地址
    private static final String VCODE_URL = Config.BASE_URL + Config.VCODE_URL;

    public static final int SUCCESS = 0;
    public static final int ERROR = 1;

    private Context context;
    private Handler vcodeHandler;

    public VcodeTask(Context context, Handler vcodeHandler) {
        this.context = context;
        this.vcodeHandler = vcodeHandler;
    }

    private void sendErrorMessage() {
        android.os.Message message = new android.os.Message();
        message.what = ERROR;
        vcodeHandler.sendMessage(message);
    }

    private void sendSuccessMessage() {
        android.os.Message message = new android.os.Message();
        message.what = SUCCESS;
        vcodeHandler.sendMessage(message);
    }

    @Override
    protected Void doInBackground(HashMap<String, String>... parameters) {
        if (!StringUtils.isEmpty(parameters[0].get("login"))) {
            HttpClient httpClient = HttpClients.createDefault();

            CookieStore cookieStore = new BasicCookieStore();
            HttpContext clientContext = new BasicHttpContext();
            clientContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

            HttpGet httpGet = new HttpGet(Config.BASE_URL + "login");

            try {
                HttpResponse response = httpClient.execute(httpGet, clientContext);
                int status = response.getStatusLine().getStatusCode();

                if (HttpStatus.OK.value() == status) {
                    XApplication application = (XApplication) context.getApplicationContext();
                    application.setCookieStore(cookieStore);
                } else {
                    sendErrorMessage();
                    return null;
                }
            } catch (Exception e) {
                sendErrorMessage();
                return null;
            }
        }

        String cellphone = parameters[0].get("phone"); //手机号码
        String type = parameters[0].get("type"); //类型

        MultiValueMap<String, String> valueMap = new LinkedMultiValueMap<String, String>();
        valueMap.add("phone", cellphone);
        valueMap.add("type", type);

        XApplication application = (XApplication) context.getApplicationContext();

        RestTemplate restTemplate = new XRestTemplate(application.getCookieStore(), context);
        restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        String url = String.format("%s?phone=%s&type=%s", VCODE_URL, cellphone, type);

        try {
            Message result = restTemplate.getForObject(url, Message.class);

            if (result != null && result.getResult().equals("0")) {
                sendSuccessMessage();
            }else
                sendErrorMessage();
        } catch (Exception e) {
            LOGE(TAG, e.getMessage());

            sendErrorMessage();
        }

        return null;
    }
}
